package com.ruoyi.system.service.impl;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRecordRequest;
import com.dingtalk.api.response.OapiAttendanceListRecordResponse;
import com.ruoyi.system.service.IAttendanceService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
public class IAttendanceServiceImpl implements IAttendanceService {


    @Override
    public OapiAttendanceListRecordResponse queryPunchCardInfo(String userId) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
        OapiAttendanceListRecordRequest req = new OapiAttendanceListRecordRequest();
        req.setUserIds(Arrays.asList(userId));
        // 获取当前时间
        Date currentDate = new Date();
        // 获取当前时间的前6天
        Date startDate = new Date(currentDate.getTime() - 6L * 24 * 60 * 60 * 1000);
        // 修改格式为 YYYY-MM-DD HH:mm:ss
        String currentDateStr = String.format("%tF %<tT", currentDate);
        String startDateStr = String.format("%tF %<tT", startDate);
        req.setCheckDateFrom(startDateStr);
        req.setCheckDateTo(currentDateStr);
        req.setIsI18n(false);
        OapiAttendanceListRecordResponse rsp = client.execute(req, getAccessToken());
        System.out.println(rsp.getBody());
        return rsp;
    }

    public static com.aliyun.dingtalkoauth2_1_0.Client create210Client() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    private String getAccessToken() throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = create210Client();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("dingc4xzf67rpxeetum7")
                .setAppSecret("KdQKouajSXoFp00nq3w2eWbtRO5r3CB2Zn89xffo7E32j1tVi9KocBTpYqvWijxp");
        GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
        return accessToken.getBody().getAccessToken();
    }
}
